// import JsonMonacoEditor from 'ey-components/packages/monaco-edit/json';
import {xhrGet, xhrPostJson} from '@/services';
import {CloudSyncOutlined, SearchOutlined} from '@ant-design/icons';
import {toJS} from '@formily/reactive';
import {
  Alert,
  Button,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  List,
  Modal,
  Radio,
  Row,
  Space,
  Spin,
  Switch,
  Table
} from "antd";
import _ from 'lodash';
import {useEffect, useRef, useState} from 'react';
import SelectIcon from "@/biz-components/select-icons";
import componentsMap from './components-map';
import {AirTicketAcctTypes, TrainTicketAcctTypes} from "@/biz-components/fee-type-Excel/acctType.data";
export const handleTableCell = (it: any, columnIndexs: any) => {
  if (it?.props?.attributes?.excelColType === 'select') {
    return {
      // editor: true,
      renderer: (instance: any, td: any, row: any, col: any, key: any, value: any) => {
        // return value;
        // const displayField = columnIndexs ? columnIndexs[`${key}Name`] : undefined;
        const item = instance.getSourceData()[row];
        const text = item[`${key}Name`]|| '';
        td.innerHTML = text || value;
        if (it?.props?.required && (!value ||  !text)) {
          td.style = 'background:red'
        }
      },
    };
  }
  return {
    type: it?.props?.attributes?.isNumber ? 'numeric' : 'text',
    renderer: (instance: any, td: any, row: any, col: any, key: any, value: any) => {
      // return value;
      // const displayField = columnIndexs ? columnIndexs[`${key}Name`] : undefined;
      // const item = instance.getSourceData()[row];
      // const text = item[`${key}Name`] || value || '';
      td.innerHTML = value;
      if (it?.props?.required && !value) {
        td.style = 'background:red'
      }
    },
  };
}
export const codeNameHeaders: any[] = ['编码', '名称']

export const yesOrNoData = [{code: '1', name: '是'}, {code: '0', name: '否'}]

export const deviceTypeData = [{code: 'PC', name: 'PC'}, {code: 'APP', name: 'APP'}];

export const data2Map = (data: any[]) => {
  const result = {};
  data?.forEach((d: any) => {
    result[d.code] = d.name;
  })
  return result;
}

export const tableRender = (key: any, colHeaders: any[], data: any[], valueMap: any) => {
  return {
    data: key,
    renderer: (instance: any, td: any, row: any, col: any, prop: any, value: any) => {
      return selectRenderer(valueMap, td, value)
    }
  }
}

export const selectRenderer = (valueMap: any, td: any, value: any) => {
  const text = valueMap[value];
  td.innerHTML = !value ? '' : (text || value);
  if (value && !text) {
    td.style = 'background:red'
  }
}


const iconModal = (props: any) => {
  const title = props?.title || '选择';
  const dataSource = (props?.dataSource || "").replace('icon-','');
  let modal: any = null;
  let editorValue = dataSource;

  const editorChange = (value: any) => {
    editorValue = value;
  }

  modal = Modal.confirm({
    title,
    content: <SelectIcon value={dataSource || ""} onChange={editorChange} exraProps={{style: {width: '100%'}}}/>,
    className: 'model-excel-modal',
    width: 600,
    onOk: () => {
      props?.onOk(`icon-${editorValue}`);
      modal?.destroy()
    }
  });
}



const SelectTable = (props: any) => {

  const {onRowClick, dataSource, multiple = false, tableSelectCallback} = props;
  const [keys, setKeys] = useState<any[]>([]);
  let searchInput: any = null;

  const onRow = (record: any) => {
    return {
      onClick: () => {
        if (!multiple) {
          onRowClick?.(record?.code);
        } else {
          let newKeys: any[] = [];
          if (keys.includes(record?.code)) {
            newKeys = _.filter(keys, (k: any) => k !== record?.code);
          } else {
            newKeys = [...keys, record?.code];
          }
          setKeys(newKeys);
          tableSelectCallback?.(newKeys)
        }
      }
    }
  }

  const getColumnSearchProps = (dataIndex: any) => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{marginBottom: 8, display: 'block'}}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined/>}
            size="small"
            style={{width: 90}}
          >
            Search
          </Button>
          <Button onClick={() => handleReset(clearFilters)} size="small" style={{width: 90}}>
            Reset
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: any) => <SearchOutlined style={{color: filtered ? '#1890ff' : undefined}}/>,
    onFilter: (value: any, record: any) => {
      return record[dataIndex]
        ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
        : ''
    },
    onFilterDropdownVisibleChange: (visible: any) => {
      if (visible) {
        setTimeout(() => searchInput?.select(), 100);
      }
    },
    render: (text: any) => text
  });

  const handleSearch = (selectedKeys: any, confirm: any, dataIndex: any) => {
    confirm?.();
  };

  const handleReset = (clearFilters: any) => {
    clearFilters?.();
  };

  const modalTableColumns = [{
    title: '编码',
    key: 'code',
    dataIndex: 'code',
    ...getColumnSearchProps('code'),
  }, {
    title: '名称',
    key: 'name',
    dataIndex: 'name',
    ...getColumnSearchProps('name'),
  }];

  const onSelectChange = (selectedRowKeys: any) => {
    setKeys(selectedRowKeys);
    tableSelectCallback?.(selectedRowKeys)
  };

  const rowSelection: any = {
    selectedRowKeys: keys,
    onChange: onSelectChange,
  };

  return <Table size="small" rowKey={'code'} rowSelection={multiple ? rowSelection : false} onRow={onRow}
                columns={modalTableColumns} dataSource={dataSource}/>
}

const modalSelect = (props: any) => {
  const title = props?.title || '选择';
  const dataSource = props?.dataSource || (props?.dataSourceFunc?.() || []);
  let modal: any = null;
  const onRowClick = (code: any) => {
    props?.onOk(code);
    modal?.destroy();
  }

  let selectedKeys: any = [];
  const tableSelectCallback = (values: any[]) => {
    selectedKeys = values;
  }

  modal = Modal.confirm({
    title,
    content: <SelectTable tableSelectCallback={tableSelectCallback} onRowClick={onRowClick} dataSource={dataSource}
                          multiple={props?.multiple}/>,
    className: 'model-excel-modal',
    okButtonProps: props?.multiple ? {} : {style: {display: 'none'}},
    width: 600,
    onOk: () => {
      props?.onOk(selectedKeys);
    }
  });
}
export const handleDepProps = (props: any, item: any, fieldKey: string) => {
  if (!props?.dep?.length || !item) {
    return {};
  }
  const params = {};
  props.dep.map(it => {
    const key = props?.depMap ? props?.depMap[it] : undefined;
    if (key) {
      params[key] = item[it] || '';
      if (fieldKey === 'seatClass') {
      // && !['TrainTicket', 'AirTicket'].includes(params[key])
        if (AirTicketAcctTypes.includes(params[key])) {
          params[key] = 'AirTicket';
        } else if (TrainTicketAcctTypes.includes(params[key])) {
          params[key] = 'TrainTicket';
        } else {
          params[key] = 'BUS';
        }
      }
    }
    return it;
  });
  return {
    api: {
      ...props?.api,
      params: {
        ...props?.api?.params,
        ...params,
      }
    },
  };
}

export const getRowCells = (map, instance) => {
  let result:any = []
  map.forEach((item:any) => {
    const {row, value,name, key, props } = item
    let nameKey = `${key}Name`
    let hasName = typeof instance.propToCol(nameKey) === 'number'
    result.push([
      row,
      key,
      value
    ])

    if(hasName) {
      result.push([
        row,
        nameKey,
        name
      ])
    }
  })
  return result
}


export const contextMenu = (props: any) => {
  return {
    items: {
      // row_above: {
      //   name: '在上方新增行'
      // },
      // row_below: {
      //   name: '在下方新增行' // Set custom text for predefined option
      // },
      // sp2: '---------',
      select: {
        name() {
          return '选择'
        },
        callback(key: any, selection: any, clickEvent: any, hotInst?:any) { // Callback for specific option
          console.log(selection);
          const that = hotInst || this;
          if (selection?.length === 1) {
            const {start, end} = selection[0];
            if (start?.row === end?.row && start?.col === end?.col) {
              const cell = that.getCellMeta(start?.row, start?.col);
              const cellValue = that.getValue();
              const selectKey = toJS(cell)?.prop;
              const selectProps = props[selectKey];
              // const allData = this.getData();
              const item = props?.detailDataSource?.length ? props?.detailDataSource[start.row] : {};
              const columnIndexs = props?.columnIndexs || {};
              const rcptFlag = that.getDataAtCell(start?.row, that.propToCol("rcptFlag"))
              const dataSource = rcptFlag === '1' ? props.dictMaps.costTypeList : props.dictMaps.costTypeListNo
              if(selectProps?.props.readOnly) {
                return
              }
              const onOk = (value: any, name: string, record:any) => {
                let updateCells = []
                updateCells.push({
                  row: start?.row,
                  key,
                  value,
                  name,
                  props: selectProps
                })
                // 国家城市联动
                if(key === "country") {
                  updateCells.push({
                    row: start?.row,
                    value: '',
                    key,
                    name: '',
                    props: selectProps
                  })
                }
                // 根据业务明细设置业务事项
                if(key === "acctType") {
                  let record = dataSource.filter((item:any) => item.code === value)[0]
                  updateCells.push({
                    row: start?.row,
                    value: record?.parentCode,
                    key: 'bizCtgry',
                    name: record?.parentName,
                    props: selectProps
                  })
                  if(typeof that.propToCol("oaFlag") === 'number') {
                    updateCells.push({
                      row: start?.row,
                      value: record?.oaFlag,
                      key: 'oaFlag',
                      props: selectProps
                    })
                  }
                  if(typeof that.propToCol("bdgtAcct") === 'number') {
                    updateCells.push({
                      row: start?.row,
                      value: record?.bdgtAcct || '',
                      name: record?.bdgtAcctName || '',
                      key: 'bdgtAcct',
                      props: selectProps
                    })
                  }
                  if(typeof that.propToCol("taxFlag") === 'number') {
                    updateCells.push({
                      row: start?.row,
                      value: record?.taxFlag || '',
                      key: 'taxFlag',
                      props: selectProps
                    })
                  }
                }
                that.setDataAtRowProp(getRowCells(updateCells, that));
              }

              const onOkMultiple = (values: any[]) => {
                // const {dataSource} = selectProps;
                // const length = values.length;
                // const dataMap: any = data2Map(dataSource);
                // if (length > 0) {
                //   for (let i = 0; i <= length; i++) {
                //     that.setDataAtCell(i + start?.row, start?.col, values[i]);
                //     that.setDataAtCell(i + start?.row, start?.col + 1, dataMap[values[i]] || values[i]);
                //   }
                // }
              }
              // 渲染组件
              if (selectProps) {
                console.log('props', props)
                const {inputValueComponentType, attributes } = selectProps?.props || {};
                let attr = {
                    ...{
                        ...attributes,
                        defaultValue: cellValue,
                    },
                    dataSource,
                    onOk: attributes?.multiple ? onOkMultiple: onOk,
                    ...handleDepProps(attributes, item, selectKey)}
                if (componentsMap && componentsMap[inputValueComponentType]) {
                    const Comp = componentsMap[inputValueComponentType];
                  Comp? Comp(attr) : null;
                  // return <Comp props={temp} />;
                }
              }
            }
          }
        }
      },
      sp1: '---------',
      remove_row: {
        name: '删除当前行', // Set custom text for predefined option
      },
    }
  }
}

export const cellChanged = (instance: any, data: any) => {
  if (data?.length > 0) {
    data.forEach((d: any) => {
      const cellIndex: any = instance?.propToCol(d[1]);
      if (d[2] !== d[3]) {
        instance.getCell(d[0], cellIndex).style = 'background:red';
        instance.getCellMeta(d[0], cellIndex).change = true;
      }
    })
  }
}

const getInstances = (searchType: any, instancesMap: any, callback: any) => {

  const initSeachPlugin = (instance: any) => {
    const searchPlugin = instance?.getPlugin('search');
    searchPlugin.setCallback(callback);
    searchPlugin.setSearchResultClass('model-excel-search-result');
    return searchPlugin;
  }

  const result: any = {};
  const keys: any[] = Object.keys(instancesMap);
  keys.forEach((k: any) => {
    if ('all' === searchType) {
      result[k] = initSeachPlugin(instancesMap[k]);
    } else {
      if (k?.startsWith(searchType)) {
        result[k] = initSeachPlugin(instancesMap[k]);
      }
    }
  })
  return result;
}

const SearchModalContent = (props: any) => {

  const {allInstnaceMap} = props;
  const [loading, setLoading] = useState<any>(null);
  const countRef: any = useRef<any>(0);
  const searchTypeRef: any = useRef<any>('like');
  const searchValueRef: any = useRef<any>('');
  const replaceValueRef: any = useRef<any>('');

  const [replace, setReplace] = useState<any>(false);

  const searchTypeChange = (e: any) => {
    searchTypeRef.current = e.target.value;
  }

  const searchValueChange = (e: any) => {
    searchValueRef.current = e.target.value;
  }

  const replaceValueChange = (e: any) => {
    replaceValueRef.current = e.target.value;
  }

  const callback: any = (instance: any, row: any, column: any, value: any, result: any) => {
    let isSearchResult = false;
    if (result) {
      if (searchTypeRef.current === 'like') {
        countRef.current += 1;
        isSearchResult = true;
        highLightTab(instance);
        if (replace) {
          instance.setDataAtCell(row, column, value.replaceAll(searchValueRef.current, replaceValueRef.current || ''));
        }
      } else {
        if (value === searchValueRef.current) {
          countRef.current += 1;
          isSearchResult = true;
          highLightTab(instance);
          if (replace) {
            instance.setDataAtCell(row, column, replaceValueRef.current || '');
          }
        }
      }
    }
    instance.getCellMeta(row, column).isSearchResult = isSearchResult;
  }

  const highLightTab = (instance: any) => {
    const pannelId: any = instance.container.parentElement.parentElement.getAttribute("id");
    if (pannelId && pannelId.includes('-panel-')) {
      const tabId: any = pannelId.split('-panel-')[1];
      if (tabId) {
        const nodes: any[] = document.querySelectorAll(".ant-tabs-tab div[id$='" + tabId + "']");
        if (nodes?.length > 0) {
          nodes.forEach((node: any) => {
            node.style.backgroundColor = 'yellow'
          })
        }
      }
    }
  }

  const onSearchOrReplace = (replace?: any) => {

    // if (replace && !replaceValueRef.current) {
    //   return;
    // }

    if (searchValueRef.current) {
      countRef.current = 0;
      setLoading(true);
      const instances: any = getInstances('all', allInstnaceMap, callback);
      Object.values(instances).forEach((search: any) => {
        search.query(searchValueRef.current);
      })
      setTimeout(() => {
        setLoading(false);
        Object.values(allInstnaceMap).forEach((inst: any) => inst?.render())
      }, 500)
    }
  }

  return <>
    <Radio.Group defaultValue={'like'} onChange={searchTypeChange} style={{marginTop: 10}}>
      <Radio.Button value="like">模糊匹配</Radio.Button>
      <Radio.Button value="equals">精确匹配</Radio.Button>
    </Radio.Group>
    <Input.Search enterButton="搜索" loading={loading || false} onSearch={() => onSearchOrReplace(false)}
                  style={{marginTop: 10}} placeholder='搜索内容' onChange={searchValueChange}/>
    <Checkbox style={{marginTop: 10}} onChange={(e: any) => setReplace(e.target.checked)}>替换</Checkbox>
    {
      replace && <>
        <Input.Search enterButton="替换" loading={loading || false} onSearch={() => onSearchOrReplace(true)}
                      style={{marginTop: 10}} placeholder='替换内容' onChange={replaceValueChange}/>
      </>
    }
    {
      null != loading && !loading && <Alert style={{marginTop: 10}}
                                            message={countRef.current === 0 ? `${searchValueRef.current} 暂无数据.` : `${searchValueRef.current} 相关${replace ? '替换' : '搜索'}结果 ${countRef.current} 条, 已高亮显示.`}
                                            type="success"/>
    }
  </>
}

// 搜索
export const SearchModal = (allInstnaceMap: any) => {

  Modal.confirm({
    icon: <SearchOutlined/>,
    title: '搜索',
    width: 600,
    content: <SearchModalContent allInstnaceMap={allInstnaceMap}/>,
    // cancelButtonProps: { style: { display: 'none' } },
    okButtonProps: {style: {display: 'none'}},

  })
}


const TmpModalContent = (props: any) => {

  const {modelCode, tmpRevert} = props;

  const [loading, setLoading] = useState<any>(false);
  const [tmp, setTmp] = useState<any>(null);
  const formRef: any = useRef<any>();

  useEffect(() => {
    if (modelCode) {
      setLoading(true);
      xhrGet('/mof/model/excelTmpFind', {modelCode}).then((res: any) => {
        if (res.result) {
          setTmp(res.result);
        }
        setLoading(false);
      })
    }
  }, [modelCode])

  const revert = () => {
    tmpRevert?.(tmp);
  }

  const formItemLayout: any = {
    labelCol: {span: 4},
    wrapperCol: {span: 20},
  };

  const formChangge = (values: any) => {
    props?.tmpCallback?.(formRef.current?.getFieldsValue(), modelCode);
  }

  return <Spin spinning={loading}>
    <Form
      ref={formRef}
      name="tmp-form"
      {...formItemLayout}
      initialValues={props?.turnonTmpValue || {}}
      onValuesChange={formChangge}
    >
      <Form.Item name="tmpTurnon" label="开启" valuePropName="checked">
        <Switch/>
      </Form.Item>
      <Form.Item name="tmpInterval" label="频率(s)">
        <InputNumber min={5} max={60}/>
      </Form.Item>
    </Form>
    <Divider/>
    <List
      header={<div>上次缓存数据</div>}
      bordered
      dataSource={!tmp ? [] : [tmp]}
      size='small'
      renderItem={item => (
        <>
          <List.Item>
            <Row style={{width: '100%'}}>
              <Col span={6}>创建人:</Col>
              <Col span={12}>{tmp?.code}</Col>
            </Row>
          </List.Item>
          <List.Item>
            <Row style={{width: '100%'}}>
              <Col span={6}>创建时间:</Col>
              <Col span={12}>{tmp?.createTime}</Col>
              <Col span={6}><Button type='primary' danger ghost size='small' onClick={revert}>恢复</Button></Col>
            </Row>
          </List.Item>
        </>
      )}
    />
  </Spin>
}

// 即时缓存
export const TmpModal = (tmpCallback: any, modelCode: any, turnonTmpValue: any, tmpRevert: any) => {

  Modal.confirm({
    icon: <CloudSyncOutlined/>,
    title: '实时缓存',
    width: 600,
    content: <TmpModalContent tmpCallback={tmpCallback} modelCode={modelCode} turnonTmpValue={turnonTmpValue}
                              tmpRevert={tmpRevert}/>,
    cancelButtonProps: {style: {display: 'none'}},

  })
}

export const str2Num = (key: any, value: any) => {
  const keys: any[] = ['sequence', 'labelCol', 'wrapperCol'];
  if (keys.includes(key) && value) {
    return parseInt(value);
  } else {
    return value;
  }
}

export const getAttachmentRemark = (type: string) => {
  let content = [];
  if (type === 'DSBX_01') { // 对私费用报销
    content = [
      '1.单笔报销金额超<b>一万</b>元，需提供<b>付款截图</b>；',
      '2.会务费相关费用事项: <b>①会议通知 ②会议合同或协议 ③会议签到表',
      '<b>④会议纪要 ⑤各类发票 ⑥垫款凭证（微信、支付宝、pos单截图）</b>；',
      '3.车辆使用费-加油费：<b>车辆起止里程时间水印照片</b>；',
      '4.滴滴、高德等打车：<b>打车行程单</b>；',
      '5.车辆使用费-保险费：<b>保单</b>；',
      '6.车辆使用费-租车费、通讯费、物业管理费：<b>合同</b>；',
      '7.物流费相关费用事项：<b>物流单</b>；',
      '8.体检费：<b>体检单据（医疗凭证）</b>；',
      '9.福利费-员关活动：<b>活动照片</b>。'
    ];
  }else if (type === 'HYBX_01') { // 会议费报销
    content = [
      '单笔报销金额超<b>一万</b>元，需提供<b>付款截图</b>。'
    ];
  }else if (type === 'ZDBX_01') { // 招待费报销
    content = [
      '单笔报销金额超<b>一万</b>元，需提供<b>付款截图</b>。'
    ];
  }
  return content;
}

export const extendProps: any[] = ['icon'];
